<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\components;
use app\models\Error;
use app\components\Fun;
use app\models\config\SiteForm;
use app\models\User;
use Yii;
use app\models\LoginForm;
use app\models\Token;
/**
 * Description of Weixin
 *
 * @author songs
 */
class Weixin {
    
    
    public $appId=''; // 必填，公众号的唯一标识
    public $appsecret='';//
    
     public function __construct($owner = null) { 
        $SiteForm =SiteForm::model();     
        $this->appId=$SiteForm->weixin_appId;
        $this->appsecret=$SiteForm->weixin_appsecret;
        
    }
    
    
    
    /**
     * 微信登录的回调登录
     * 获取code
    */
    public function Login(){
       if(!isset($_GET['state'])||empty($_GET['code'])||$_GET['state']!=='STATE'){
           Error::addmsg('微信登录参数错误'.  print_r($_GET,true));
           Fun::showmsg('登录参数错误');
       }
       $access_token_data=  $this->Getaccess_token($_GET['code']);
    //   Error::addmsg(print_r($access_token_data,true));
       $url='https://api.weixin.qq.com/sns/userinfo?access_token='.
               $access_token_data['access_token']
               .'&openid='.$access_token_data['openid'].'&lang=zh_CN';
       $userData=Fun::curl_get($url);
     ///  Error::adderrormsg($userData);
       $userJson=  json_decode($userData,true);       
       /**
        * 判断是否存在这个微信登录
        * 如果没有绑定用户数据,返回false
        * 如果有数据,并检查是否需要更新
       */
       if($data=$this->addUser($userJson,$access_token_data['access_token'])){
           $data->login();
            /// Yii::$app->user->login($data, 3600*24*LoginForm::rememberMeDay);
              Yii::$app->response->redirect(Yii::$app->user->returnUrl);
              Yii::$app->end();
       }else{
           Fun::showmsg('登录失败');
       }
       
      // Error::addmsg(print_r($userData,true));
    }
    
    /**
     * 判断是否存在这个微信登录
     *  如果没有绑定用户数据,返回false
    */
   private function addUser($userJson,$access_token){
     ///  print_r($userJson);exit;
      /// Error::addmsg(print_r($userJson,true));
       $user=  User::find()->where([
           'bindtype'=>User::bindtype_weixin,
           'open_id'=>$userJson['openid']
           ])->one();
       if($user){
           $up=false;
           if($user->username!=$userJson['nickname']){
              $user->username= $userJson['nickname'];
              $up=true;
           }
           if($user->access_token!=$access_token){
               $user->access_token=$access_token;
               $up=true;
           }
           if($user->avatar!=$userJson['headimgurl']){
              $user->avatar= $userJson['headimgurl'];
              $up=true;
           }
           if($up){
               $user->update();
           }
        
       }else{
            $user=new User;
            $user->username= $userJson['nickname'];
            $user->time=time();
            $user->open_id=$userJson['openid'];
            $user->avatar=$userJson['headimgurl'];
            $user->access_token=$access_token;
            $user->bindtype=User::bindtype_weixin;
            $user->save();
       }
          return $user;
   }

   





   /**
     * 根据code获取access_token
     */
private function Getaccess_token($code){
    $href='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.
            $this->appId.'&secret='.
            $this->appsecret.
            '&code='.$code.'&grant_type=authorization_code';
    $data= Fun::curl_get($href);
    return json_decode($data,true);
}

    



    /**
     * 生成登录的链接
    */
    public function getLoginHref(){
         return 'http://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appId
            .'&redirect_uri='.urlencode(Lcms::getHost().Lcms::getWeb().'home/public/weixin')
            .'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    }
    
    
    
    /**
     * 返回微信的weixin_access_token
     */
    public function Get_Weixin_access_token(){
        $token=new Token();
        $token->appid=  $this->appId;
        $token->appsecret=  $this->appsecret;
        return $token->get_weixin_access_token();
    }
    
    
    
    /**
     * 根据接口下载图片
     * $media_id为资源的id
    */
   public function downloadPic($media_id){
       $url='http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$this->Get_Weixin_access_token().'&media_id='.$media_id;
       $d=Fun::curl_get($url);
       
           $fp2=@fopen('fffffff.jpg','a');
            fwrite($fp2,$d);
            fclose($fp2);
            var_dump($fp2);exit;
       
       echo $d;exit;
   }
    
    
}
